package com.tile.v2;

public class GetTileCoord {
	
	public static double getMercatorLatitude(double lati, int zoom){
		double maxlat = Math.PI;
	    double lat = lati;
	    if (lat > 90){
	        lat = lat - 180;
	    }
	    if (lat < -90){
	        lat = lat + 180;
	    }
	    // 转换度数到弧度
	    double phi = Math.PI * lat / 180.0;

	    //temp = math.tan(math.pi / 4.0 + phi / 2.0);
	    //res = math.log(temp);
	    //下面这一句是上面的合并
	    double res = 0.5 * Math.log((1 + Math.sin(phi)) / (1 - Math.sin(phi)));

	    int maxTileY = (int)Math.pow(2, zoom);

	    double result = (int)(((1 - res / maxlat) / 2) * (maxTileY));
	    return result;
	}
	
	
	public static Tile getTile(double longitude, double latitude, int zoom){
	    longitude = 180+longitude;
	    double longTileSize = 360.0/(Math.pow(2,(zoom)));
	    double tilex =  longitude/longTileSize;
	    double tiley = getMercatorLatitude(latitude, zoom);

	    int x = (int)(Math.floor(tilex));
	    int y = (int)(Math.floor(tiley));
	    
	    //"&x=" + x + "&y=" + y + "&z=" + zoom + "&s="
	    Tile tile = new Tile(x, y, zoom);
	    return tile;
	}
	
	public static void main(String[] args) {
		Tile tile = GetTileCoord.getTile(120, 37, 3);
		System.out.println(tile.getURL());
	}
}
